<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Search, Edit, Delete, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { addCourseClassify, getCoursePage, deleteCourseById } from '@/api/course'

const router = useRouter()

// 课程列表
const courses = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 新增分类弹窗相关
const classifyDialogVisible = ref(false)
const classifyForm = ref({ classifyName: '' })
const classifyFormRef = ref(null)
const classifyRules = { classifyName: [{ required: true, message: '请输入分类名称', trigger: 'blur' }] }

// 加载课程列表（分页）
const loadCourses = async () => {
  try {
    const res = await getCoursePage({
      page: currentPage.value,
      pageSize: pageSize.value,
      courseName: searchKeyword.value
    })
    if (res.code === 0 || res.code === 200) {
      courses.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 搜索课程
const handleSearch = () => {
  currentPage.value = 1
  loadCourses()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadCourses()
}

// 分页事件
const handlePageChange = (page) => {
  currentPage.value = page
  loadCourses()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCourses()
}

// 删除课程
const deleteCourse = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
  confirmButtonText: '是',
  cancelButtonText: '否',
  type: 'warning'
})
    const res = await deleteCourseById(row.courseId)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页数据被删空且不是第一页，自动跳到上一页
      if (courses.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      loadCourses() // 刷新课程列表
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 查看课程
const viewCourse = (row) => {
  router.push(`/teacher/courses/${row.courseId}/chapters`)
}

// 编辑课程
const editCourse = (row) => {
  router.push(`/teacher/courses/edit/${row.courseId}`)
}

// 初始化
onMounted(() => {
  loadCourses()
})
</script>

<template>
  <div class="courses-container">
    <el-card class="courses-card">
      <template #header>
        <div class="card-header">
          <h2>课程管理</h2>
          <div>
            <el-button type="primary" @click="router.push('/teacher/create-course')">
              <el-icon><plus /></el-icon>
              新建课程
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程名称"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 课程列表 -->
      <el-table :data="courses" style="width: 100%">
        <el-table-column prop="courseName" label="课程名称" min-width="200" />
        <el-table-column prop="courseClassify" label="分类" width="120" />
        <el-table-column prop="courseDescription" label="描述" min-width="200" />
        <el-table-column prop="courseCover" label="封面" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.courseCover"
              :src="row.courseCover"
              style="width: 60px; height: 40px; object-fit: cover;"
              fit="cover"
              :preview-src-list="[row.courseCover]"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewCourse(row)">
              <el-icon><view /></el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="editCourse(row)">
              <el-icon><edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" link @click="deleteCourse(row)">
              <el-icon><delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; display: flex; justify-content: flex-end;"
      />
    </el-card>
  </div>
</template>

<style scoped>
.courses-container {
  padding: 32px 32px 32px 32px;
  background: linear-gradient(180deg, #f8fbff 0%, #f5f7fa 100%);
  min-height: 100vh;
}
.courses-card {
  margin-bottom: 24px;
  border-radius: 16px;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.08);
  background: #fff;
  padding: 0 0 10px 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.card-header h2 {
  margin: 0;
  font-size: 22px;
  color: #222;
  font-weight: bold;
  letter-spacing: 1px;
}
.el-table {
  border-radius: 12px;
  overflow: hidden;
  background: #fff;
}
.el-table th, .el-table td {
  font-size: 15px;
  color: #333;
  background: #f8fbff;
}
.el-table th {
  font-weight: 700;
  background: #f0f7ff;
}
.el-table tr {
  transition: background 0.2s;
}
.el-table tr:hover {
  background: #f5faff;
}
.el-button[type="primary"], .el-button--primary {
  background: linear-gradient(90deg, #409eff 60%, #66b1ff 100%);
  border: none;
  color: #fff;
  border-radius: 20px;
  font-weight: 500;
  transition: box-shadow 0.2s;
}
.el-button[type="primary"]:hover, .el-button--primary:hover {
  box-shadow: 0 2px 8px rgba(64,158,255,0.15);
}
.el-button[type="success"], .el-button--success {
  border-radius: 20px;
  font-weight: 500;
}
.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.06);
  padding: 14px 18px;
}
.search-input {
  width: 300px;
  border-radius: 20px;
  overflow: hidden;
}
.el-pagination {
  background: #fff;
  border-radius: 12px;
  padding: 8px 18px;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.06);
}
.el-dialog {
  border-radius: 16px !important;
  box-shadow: 0 8px 32px 0 rgba(64,158,255,0.12) !important;
}
.el-form-item__label {
  font-weight: 600;
  color: #409eff;
}
.el-input, .el-input__inner {
  border-radius: 12px !important;
}
.el-dialog__footer {
  padding-bottom: 18px;
}
@media screen and (max-width: 900px) {
  .courses-container {
    padding: 10px 2vw 20px 2vw;
  }
  .courses-card {
    padding: 0 0 4px 0;
  }
  .search-bar {
    flex-direction: column;
    gap: 8px;
    padding: 10px 6px;
  }
}
</style> 